package com.example.hrsystem.ui.approval.overtime;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hrsystem.R;
import com.example.hrsystem.workflow.ApprovalViewModel;
import com.example.hrsystem.workflow.model.OvertimeRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * 加班申请列表Activity
 * 显示用户所有加班申请记录
 */
public class OvertimeRequestListActivity extends AppCompatActivity {
    private ApprovalViewModel viewModel;
    private RecyclerView recyclerView;
    private OvertimeRequestAdapter adapter;
    private ProgressBar progressBar;
    private TextView emptyStateTextView;
    private TextView errorTextView;
    private Button newRequestButton;
    
    private int currentUserId = 2; // 统一使用用户ID 2，与其他功能保持一致
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_overtime_request_list);

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ApprovalViewModel.class);

        // 初始化UI组件
        initUI();

        // 设置RecyclerView
        setupRecyclerView();

        // 设置按钮点击事件
        setupButtonListeners();

        // 加载加班申请数据
        loadOvertimeRequests();

        // 观察数据变化
        observeDataChanges();
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        recyclerView = findViewById(R.id.overtime_request_recycler_view);
        progressBar = findViewById(R.id.progress_bar);
        emptyStateTextView = findViewById(R.id.empty_text_view);
        errorTextView = findViewById(R.id.error_text_view);
        newRequestButton = findViewById(R.id.new_request_button);
    }

    /**
     * 设置RecyclerView
     */
    private void setupRecyclerView() {
        adapter = new OvertimeRequestAdapter(new ArrayList<>(), new OvertimeRequestAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(OvertimeRequest overtimeRequest) {
                // 点击加班申请项，跳转到详情页
                Intent intent = new Intent(OvertimeRequestListActivity.this, OvertimeRequestDetailActivity.class);
                intent.putExtra("overtime_request_id", overtimeRequest.getId());
                startActivity(intent);
            }
        });
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }

    /**
     * 设置按钮点击事件
     */
    private void setupButtonListeners() {
        // 新建加班申请按钮
        newRequestButton.setOnClickListener(v -> {
            Intent intent = new Intent(OvertimeRequestListActivity.this, OvertimeRequestFormActivity.class);
            startActivity(intent);
        });


    }

    /**
     * 加载加班申请数据
     */
    private void loadOvertimeRequests() {
        showLoadingState();
        try {
            // 获取当前用户的所有加班申请
            List<OvertimeRequest> requests = viewModel.getOvertimeRequestsByApplicant(currentUserId);
            if (requests != null) {
                updateRecyclerView(requests);
            } else {
                showEmptyState();
            }
        } catch (Exception e) {
            showErrorState("加载加班申请失败: " + e.getMessage());
        } finally {
            progressBar.setVisibility(View.GONE);
        }
    }

    /**
     * 观察数据变化
     */
    private void observeDataChanges() {
        // 观察加载状态
        viewModel.getIsLoading().observe(this, isLoading -> {
            if (isLoading) {
                showLoadingState();
            } else {
                progressBar.setVisibility(View.GONE);
            }
        });

        // 观察错误信息
        viewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                showErrorState(errorMessage);
            }
        });
    }

    /**
     * 更新RecyclerView数据
     */
    private void updateRecyclerView(List<OvertimeRequest> overtimeRequests) {
        if (overtimeRequests.isEmpty()) {
            showEmptyState();
        } else {
            adapter.setOvertimeRequests(overtimeRequests);
            adapter.notifyDataSetChanged();
            showRecyclerView();
        }
    }

    /**
     * 显示加载状态
     */
    private void showLoadingState() {
        recyclerView.setVisibility(View.GONE);
        emptyStateTextView.setVisibility(View.GONE);
        errorTextView.setVisibility(View.GONE);

        progressBar.setVisibility(View.VISIBLE);
    }

    /**
     * 显示空状态
     */
    private void showEmptyState() {
        recyclerView.setVisibility(View.GONE);
        emptyStateTextView.setVisibility(View.VISIBLE);
        errorTextView.setVisibility(View.GONE);

        progressBar.setVisibility(View.GONE);
    }

    /**
     * 显示错误状态
     */
    private void showErrorState(String errorMessage) {
        recyclerView.setVisibility(View.GONE);
        emptyStateTextView.setVisibility(View.GONE);
        errorTextView.setText(errorMessage);
        errorTextView.setVisibility(View.VISIBLE);

        progressBar.setVisibility(View.GONE);
    }

    /**
     * 显示RecyclerView
     */
    private void showRecyclerView() {
        recyclerView.setVisibility(View.VISIBLE);
        emptyStateTextView.setVisibility(View.GONE);
        errorTextView.setVisibility(View.GONE);

        progressBar.setVisibility(View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 在Activity恢复时重新加载数据，以获取最新申请列表
        loadOvertimeRequests();
    }
}